myApp.controller('ProjectController', function ($scope, $stateParams, $http, $sce, $interval, $uibModal, ngDialog, $rootScope) {
    $scope.ws = null;
    $scope.msgQueue = new Array();
    //ws重连定时
    $scope.wsTimer = null;
    //页面数据
    $scope.info = {};
    $scope.info.tab3 = "构建日志";
    $scope.info.tabs = ["版本列表", "SQLs", "Excels", $scope.info.tab3];
    //选中的工程
    $scope.info.selectProject = $stateParams.selectProject;
    $scope.info.trunkInfo = {};
    $scope.info.projectInfo = {};
    //工程列表
    $scope.info.trunkList = [];
    $scope.info.projectList = [];
    //工程配置tip内容
    $scope.info.projectTip = "";
    //工程版本列表
    $scope.info.editionList = [];
    //版本保存最大数
    $scope.info.editionCountMax = "5";
    //执行中状态
    $scope.info.isRunning = false;
    //tab页选中序号
    $scope.info.tabIndex = 0;
    //文件上传
    $scope.info.fileInputType = '';
    //工程sql文件列表
    $scope.info.sqls = [];
    //工程excel文件列表
    $scope.info.excels = [];

    $scope.info.buildLog = "";
    //工程访问sonar的地址 默认为空 当构建过程中sonar失败时,才会显示
    $scope.info.sonarUrl = "";

    //测试通过后 跳板机推送状态 in_push时  测试通过按钮不可点
    $scope.info.pushStatus = "";
    $scope.info.pushDesc = "";

    //工程项目关联的ucloud列表
    $scope.info.ucList = [];
    //plan信息
    $scope.info.planInfo = {};
    //plan工程信息
    $scope.info.planPro = null;

    $scope.$on("$destroy", function () {
        $interval.cancel($scope.mqTimer);
        wsWithReClose(wsObjs[0]);
        removeStorage('project_go_back');
    });

    //获取工程所在项目关联的ucloud列表
    $scope.getUcloudList = function () {
        $scope.info.ucList = [];
        $scope.info.planPro = null;
        doBeetleGet($http, $uibModal, beetle_plan_url + '/project/getProjectInfo?token_id=' + getTokenId() + '&project_name=' + $scope.info.projectInfo.projectName, function (data) {
            if (!data.success) {
                return
            }
            if (data.data.plan_id == null) {
                return
            }
            $scope.info.planPro = data.data;
            doBeetleGet($http, $uibModal, beetle_plan_url + '/project_plan/getPlanList?token_id=' + getTokenId() + '&plan_id=' + $scope.info.planPro.plan_id + '&isShowOnline=true', function (data) {
                if (!data.success) {
                    return
                }
                $scope.info.planInfo = data.data[0];
            });
            doBeetleGet($http, $uibModal, ucloud_master_url + '/api/v1/apply_record?token_id=' + getTokenId() + '&isOnlyOneMouth=false&plan_id=' + $scope.info.planPro.plan_id, function (data) {
                if (!data.success) {
                    return
                }
                angular.forEach(data.data, function (record) {
                    if (record.agent_ip != null && record.agent_ip != '') {
                        $scope.info.ucList.push(record);
                    }
                })
            })
        });
    };

    $scope.goToUcloudPage = function (uc) {
        window.location.href = "#/menu/newucList/" + uc.agent_ip;
    };

    loadInfo();

    $scope.showGoBack = function () {
        var project_go_back = getStorage('project_go_back');
        if (project_go_back != '') {
            return true;
        } else {
            return false;
        }
    };

    //初始化文件上传控件
    initFileInput("sqlFile", ['sql']);
    initFileInput("excelFile", ['xls', 'xlsx']);

    //选择工程
    $scope.projectSelect = function () {
        window.location.href = "#/menu/project/" + $scope.info.projectInfo.projectName;
    };
    $scope.trunkSelect = function () {
        window.location.href = "#/menu/project/" + $scope.info.trunkInfo.projectName;
    };
    //执行构建
    $scope.doBuild = function () {
        $scope.info.isRunning = true;
        $scope.info.buildLog = "";
        $scope.info.sonarUrl = "";
        $http.post(java_url + '/beetle/project/doBuild', {
            projectName: $scope.info.selectProject,
            tokenId: getTokenId()
        }).success(function (data) {
            if (data.code != '0') {
                alert(data.desc);
                return;
            }
            ;
        });
    };
    //标记提测
    $scope.toTest = function (type, edition) {
        //取消提交测试
        if (!type) {
            openDialog(ngDialog, $scope, "确定要取消提测版本" + edition.editionNum + "吗?", true, function (val) {
                if (!val) {
                    return;
                }
                doBeetleGet($http, $uibModal, beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + $scope.info.projectInfo.projectName + '&type=cancel_to_test&edition_num=' + edition.editionNum + '&plan_id=' + $scope.info.planPro.plan_id, function (data) {
                    loadInfo();
                    if (!data.success) {
                        openDialogAlert(ngDialog, $scope, data.msg);
                    }
                });
            });
        } else {
            //提交测试
            var saveFun = function () {
                loadInfo();
            };
            $rootScope.editionToTestTemplate($scope.info.projectInfo.projectName, 'TEST', saveFun);
        }
    };

    $scope.updateTestStatusConfirm = function (edition, flag) {
        var msg = flag ? "测试通过" : "测试不通过";
        openDialog(ngDialog, $scope, "确定要将版本" + edition.editionNum + "标记为" + msg + "么?", true, function (f) {
            if (!f) {
                return;
            }
            $scope.updateTestStatus(edition, flag)
        });
    };

    //测试通过/不通过
    $scope.updateTestStatus = function (edition, flag) {
        $scope.info.isRunning = true;
        var type = 'cancel_hand_over';
        if (flag) {
            $scope.info.pushStatus = "in_push";
            $scope.info.pushDesc = "";
            type = 'hand_over';
        }
        ;

        doBeetleGet($http, $uibModal, beetle_plan_url + '/project/updateProjectEdition?token_id=' + getTokenId() + '&project_name=' + $scope.info.projectInfo.projectName + '&type=' + type + '&edition_num=' + edition.editionNum + '&plan_id=' + $scope.info.planPro.plan_id, function (data) {
            loadInfo();
            if (!data.success) {
                openDialogAlert(ngDialog, $scope, data.msg);
            }
        });
    };
    //编辑备注
    $scope.editDesc = function (type, object) {
        if (!object.modifiable) {
            object.modifiable = true;
            return;
        }
        object.modifiable = false;
        if (type == 'edition') {
            $http.post(java_url + '/beetle/project/editEditionDesc', {
                projectName: $scope.info.selectProject,
                editionNum: object.editionNum,
                desc: object.desc,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert(data.desc);
                    return;
                }
                ;
            });
        } else if (type == 'sql' || type == 'excel') {
            $http.post(java_url + '/beetle/project/editProjectFileDesc', {
                projectName: $scope.info.selectProject,
                type: type,
                fileName: object.fileName,
                desc: object.desc,
                tokenId: getTokenId()
            }).success(function (data) {
                if (data.code != '0') {
                    alert(data.desc);
                    return;
                }
                ;
            });
        }
        ;
    };
    //删除文件
    $scope.delFile = function (type, object) {
        if (!confirm("确认要删除文件" + object.fileName + "么?")) {
            return;
        }
        ;

        $scope.info.isRunning = true;
        $http.post(java_url + '/beetle/project/delProjectFile', {
            projectName: $scope.info.selectProject,
            type: type,
            fileName: object.fileName,
            tokenId: getTokenId()
        }).success(function (data) {
            loadSQLorExcelList(type);
            $scope.info.isRunning = false;
            if (data.code != '0') {
                alert(data.desc);
                return;
            }
            ;
        });
    };
    //tab切换
    $scope.tabClick = function (index) {
        $scope.info.tabIndex = index;

        $scope.info.fileInputType = '';
        if ($scope.info.tabIndex == 1) {
            loadSQLorExcelList('sql');
            $scope.info.fileInputType = 'sql';
        } else if ($scope.info.tabIndex == 2) {
            loadSQLorExcelList('excel');
            $scope.info.fileInputType = 'excel';
        }
        ;
    };

    //下载单个文件
    $scope.downloadFile = function (name) {
        window.location.href = java_url + "/beetle/project/downloadProjectFile?projectName=" + $scope.info.selectProject
            + "&type=" + $scope.info.fileInputType + "&fileName=" + name + "&tokenId=" + getTokenId();
    };
    //下载打包的压缩文件
    $scope.downloadZipFile = function () {
        window.location.href = java_url + "/beetle/project/downloadProjectFile?projectName=" + $scope.info.selectProject
            + "&type=" + $scope.info.fileInputType + "&downloadAll=true" + "&tokenId=" + getTokenId();
    };

    //访问sonar
    $scope.openSonar = function () {
        if ($scope.info.sonarUrl == "") {
            alert('sonar访问地址为空。');
            return;
        }
        ;

        window.open($scope.info.sonarUrl);
    };

    //加载工程信息列表及选中工程版本信息,用于进入页面及刷新页面
    function loadInfo() {
        setTimeout(function () {
            $scope.info.selectTrunk = $scope.info.selectProject == '' ? '' : $scope.info.selectProject.split('_')[0];
            //获取主干工程列表
            $http.post(java_url + '/beetle/project/projectInfoList', {
                tokenId: getTokenId(),
                onlyTrunk: true
            }).success(function (data) {
                if (data.code != '0') {
                    alert("获取工程信息失败,desc=" + data.desc);
                    return;
                }
                $scope.info.trunkList = data.data.list;
                $scope.info.trunkInfo = {};
                $scope.info.selectTrunk = $scope.info.selectTrunk == '' ? $scope.info.trunkList[0].projectName : $scope.info.selectTrunk;
                angular.forEach($scope.info.trunkList, function (pro) {
                    if (pro.projectName == $scope.info.selectTrunk) {
                        $scope.info.trunkInfo = pro;
                    }
                });

                if (typeof $scope.info.trunkInfo.projectName == 'undefined') {
                    alert("工程" + $scope.info.selectTrunk + "不存在");
                    $scope.info.selectProject = $scope.info.trunkList[0].projectName;
                    loadInfo();
                    return;
                }
                ;

                //获取主干下工程列表
                $http.post(java_url + '/beetle/project/projectListByTrunk', {
                    tokenId: getTokenId(),
                    trunkName: $scope.info.selectTrunk
                }).success(function (data) {
                    if (data.code != '0') {
                        alert("获取工程信息失败,desc=" + data.desc);
                        return;
                    }
                    ;
                    $scope.info.projectList = data.data.list;
                    $scope.info.editionCountMax = data.data.editionCountMax;
                    $scope.info.projectInfo = {};
                    $scope.info.selectProject = $scope.info.selectProject == '' ? $scope.info.projectList[0].projectName : $scope.info.selectProject;
                    for (var i = 0; i < $scope.info.projectList.length; i++) {
                        var proInfo = $scope.info.projectList[i];
                        if ($scope.info.selectProject == proInfo.projectName) {
                            $scope.info.projectInfo = proInfo;
                            break;
                        }
                        ;
                    }
                    ;

                    if (typeof $scope.info.projectInfo.projectName == 'undefined') {
                        alert("工程" + $scope.info.selectProject + "不存在");
                        $scope.info.selectProject = $scope.info.projectList[0].projectName;
                        loadInfo();
                        return;
                    }
                    ;

                    refreshRunStatus();
                    // $scope.registerMessageQueue();
                    $scope.wsWithReConnect();
                    var tip = "svn地址:" + $scope.info.projectInfo.vcsPath + "<br>" +
                        "工程类型:" + $scope.info.projectInfo.packageType + "<br>" +
                        "subModule:" + $scope.info.projectInfo.subModule + "<br>" +
                        "环境配置工程名:" + $scope.info.projectInfo.configProjectName + "<br>";
                    if ('ant_android' != $scope.info.projectInfo.packageType) {
                        tip = tip + "配置文件相对路径:" + $scope.info.projectInfo.configPath + "<br>";
                    }
                    if ('maven_war' == $scope.info.projectInfo.packageType || 'spring_boot_jar' == $scope.info.projectInfo.packageType) {
                        $scope.info.projectTip = $sce.trustAsHtml(tip + "发布包名称:" + $scope.info.projectInfo.warName + "<br>");
                    } else if ('php' == $scope.info.projectInfo.packageType || 'ant_android' == $scope.info.projectInfo.packageType) {
                        $scope.info.projectTip = $sce.trustAsHtml(tip + "发布包名称:" + $scope.info.projectInfo.packageName + "<br>");
                    }

                    $scope.info.pushStatus = $scope.info.projectInfo.pushStatus;
                    $scope.info.pushDesc = $scope.info.projectInfo.pushDesc;

                    loadEditionList();
                    $scope.getUcloudList();
                });
            });
        }, 500);
    };

    //加载工程版本信息列表
    function loadEditionList() {
        $http.post(java_url + '/beetle/project/editionInfoList', {
            projectName: $scope.info.selectProject,
            tokenId: getTokenId()
        }).success(function (data) {
            if (data.code != '0') {
                alert("获取工程信息失败,desc=" + data.desc);
                return;
            }
            ;
            $scope.info.editionList = data.data.list;
            angular.forEach($scope.info.editionList, function (edition) {
                var path = 'beetle/' + getTrunkName($scope.info.selectProject) + "/" + $scope.info.selectProject + "/"
                    + edition.editionNum + "/";
                if ('maven_war' == $scope.info.projectInfo.packageType) {
                    edition.tip = path + $scope.info.projectInfo.warName + ".war";
                } else if ('php' == $scope.info.projectInfo.packageType
                    || 'ant_android' == $scope.info.projectInfo.packageType) {
                    edition.tip = path + $scope.info.projectInfo.packageName + ".zip";
                } else if ('spring_boot_jar' == $scope.info.projectInfo.packageType) {
                    edition.tip = path + $scope.info.projectInfo.warName + ".jar";
                }
            });
        });
    };

    //加载sql/excel列表
    function loadSQLorExcelList(type) {
        if (type == 'sql') {
            $scope.info.sqls = [];
        } else if (type == 'excel') {
            $scope.info.excels = [];
        }
        ;

        $http.post(java_url + '/beetle/project/projectFileList', {
            projectName: $scope.info.selectProject,
            type: type,
            tokenId: getTokenId()
        }).success(function (data) {
            if (data.code != '0') {
                alert(data.desc);
                return;
            }
            ;
            if (type == 'sql') {
                $scope.info.sqls = data.data.list;
            } else if (type == 'excel') {
                $scope.info.excels = data.data.list;
            }
            ;
        });
    };

    //初始化文件上传控件
    function initFileInput(id, allowedFileExtensions) {
        var input = $("#" + id);
        input.fileinput({
            language: 'zh', //设置语言
            uploadUrl: java_url + "/beetle/project/uploadFile?tokenId=" + getTokenId(),
            showUpload: true,
            uploadAsync: true,
            // allowedFileExtensions : ['jpg', 'png','gif'],//接收的文件后缀
            allowedFileExtensions: allowedFileExtensions,//接收的文件后缀
            uploadExtraData: function () {
                return {
                    projectName: $scope.info.selectProject,
                    type: $scope.info.fileInputType
                };
            }
        }).on("fileuploaded", function (event, data, previewId, index) {
            if (data.response.code != '0') {
                alert(data.response.desc);
                return;
            }
            ;

            if ($scope.info.tabIndex == 1) {
                loadSQLorExcelList('sql');
            } else if ($scope.info.tabIndex == 2) {
                loadSQLorExcelList('excel');
            }
            ;
        });
    };

    function refreshRunStatus() {
        if ($scope.info.projectInfo.buildStatus == 'on_build'
            || $scope.info.projectInfo.buildStatus == 'in_queue') {
            $scope.info.isRunning = true;
        } else {
            $scope.info.isRunning = false;
        }
        ;
    };

    //ws带自动重连
    $scope.wsWithReConnect = function () {
        var id = "project-" + $scope.info.selectProject + "-build";
        $scope.msgQueue = new Array();
        var wsObj = wsObjs[0];
        wsWithReConnect(wsObj, function () {
            wsObj.obj.send(id);
        }, function (event) {
            $scope.msgQueue.push(event);
        });
    };

    var logDiv = document.getElementById("log_div");
    $scope.mqTimer = $interval(function () {
        var event = $scope.msgQueue.shift();
        if (!event) {
            return;
        }
        ;
        var data = JSON.parse(event.data);
        if (data.body.projectName != $scope.info.selectProject) {
            return;
        }
        ;

        var message = '';
        if (data.head.type == 'project_build_log') {//输出日志
            if (data.body.message.indexOf("[ERROR]") == 0
                || data.body.message.indexOf("[INFO] BUILD FAILURE") == 0
                || data.body.message.indexOf("BUILD FAILED") == 0
                || data.body.message.indexOf("ERROR") == 0) {
                message = "<div msgType='error'>" + data.body.message + "</div>";
            } else if (data.body.message.indexOf("[INFO] BUILD SUCCESS") == 0
                || data.body.message.indexOf("BUILD SUCCESSFUL") == 0) {
                message = "<div msgType='success'>" + data.body.message + "</div>";
            } else if (data.body.message.indexOf("更新svn代码") != -1) {
                message = "<div msgType='version'>" + data.body.message + "</div>";
            } else {
                message = "<div msgType='info'>" + data.body.message + "</div>";
            }
            ;

        } else if (data.head.type == 'project_build_status') {//输出构建状态
            $scope.info.projectInfo.buildStatus = data.body.status;
            refreshRunStatus();
            if ("on_build" == $scope.info.projectInfo.buildStatus) {
                $scope.info.tabIndex = 3;

                message = "<div msgType='info'>" + "工程" + data.body.showProjectName + "开始构建......" + "</div>"
                    + "<div msgType='info'>" + "正在更新工程代码......" + "</div>";

            } else if ("build_failed" == $scope.info.projectInfo.buildStatus) {

                $scope.info.tabIndex = 3;

                message = "<div msgType='error'>" + "工程" + data.body.showProjectName + "构建失败.请检查工程代码和工程配置信息!" + "</div>";

            } else if ("build_success" == $scope.info.projectInfo.buildStatus) {

                $scope.info.tabIndex = 3;

                message = "<div msgType='success'>" + "Congratulation! 工程" + data.body.showProjectName + "构建成功." + "</div>";

                if ($scope.info.selectProject == data.body.showProjectName) {
                    loadEditionList();
                }
                ;

            } else if ("in_queue" == $scope.info.projectInfo.buildStatus) {
                $scope.info.tabIndex = 3;
                message = "<div msgType='info'>" + "工程" + data.body.showProjectName + "构建线程正在排队中......" + "</div>";
            }
            ;
        } else if (data.head.type == 'project_sonar_url') {//sonar失败时显示sonarurl
            $scope.info.sonarUrl = "";
            $scope.info.sonarUrl = data.body.url;
        } else if (data.head.type == 'project_push_status') {//工程跳板机推送状态
            $scope.info.pushStatus = "";
            $scope.info.pushStatus = data.body.status;
            $scope.info.pushDesc = "";
            $scope.info.pushDesc = data.body.desc;
        }
        ;

        $scope.info.buildLog = $sce.trustAsHtml($scope.info.buildLog + message);
        setTimeout(function () {
            logDiv.scrollTop = logDiv.scrollHeight;
        }, 50);
    }, 50);

    $scope.openShowLogModal = function (size) {
        var info = $scope.info.selectProject;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'BuildLogModal.html',
            controller: 'BuildLogModalCtrl',
            size: size,
            resolve: {
                info: function () {
                    return info;
                }
            }
        });
    };

    //推送失败 重新推送
    $scope.rePush = function (edition) {
        $scope.info.isRunning = true;
        $scope.info.pushStatus = "in_push";
        $scope.info.pushDesc = "";

        $http.post(java_url + '/beetle/pushRecord/createPush', {
            projectName: $scope.info.selectProject,
            editionNum: edition.editionNum,
            tokenId: getTokenId(),
            testPass: true
        }).success(function (data) {
            loadInfo();
            if (data.code != '0') {
                alert(data.desc);
                return;
            }
            ;
        });
    };

    $scope.toPlan = function (id) {
        if ($scope.info.planInfo.isEmergency == '0') {
            window.location.href = "#/menu/emergencyInfo/" + id;
        } else if ($scope.info.planInfo.isEmergency == '1') {
            window.location.href = "#/menu/plan_ProjectList/" + id;
        }
    };
});
myApp.controller('BuildLogModalCtrl', function ($scope, $uibModalInstance, $http, info) {
    $scope.logPath = "";
    $scope.log = "";
    if (info == "") {
        $scope.log = "参数错误!工程名为空";
    } else {
        $http.post(java_url + '/beetle/project/getBuildLog', {
            projectName: info,
            tokenId: getTokenId()
        }).success(function (data) {
            $scope.log = "";
            $scope.logPath = "";
            if (data.code != '0') {
                $scope.log = data.desc;
                $scope.logPath = data.data.logPath;
            } else {
                $scope.log = data.data.log;
                $scope.logPath = data.data.logPath;
            }
        });
    }
    ;
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});